import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { GoodsItem } from '../types/cart'

export const useCartStore = defineStore('cart', () => {
	const cartList = ref([] as GoodsItem[])

	// 加入购物车
	const addToCart = (goodsItem : GoodsItem) => {
		const oldGoods = cartList.value.find(item => item.proid === goodsItem.proid)
		if (oldGoods) {
			oldGoods.number += goodsItem.number
		} else {
			cartList.value.push(goodsItem)
		}
	}

	// 修改购物车中商品的选中状态
	/**
	 * goodsItem {proid: 'xxx', checked: true/false}
	 */
	const changeGoodsState = (goodsItem : Partial<GoodsItem>) => {
		const oldGoods = cartList.value.find(item => item.proid === goodsItem.proid)
		if (oldGoods) {
			oldGoods.checked = goodsItem.checked
		}
	}

	// 更改购物车中商品的数量
	/**
	 * goodsItem {proid: 'xxx', number: 2}
	 */
	const changeGoodsNumber = (goodsItem : Partial<GoodsItem>) => {
		const oldGoods = cartList.value.find(item => item.proid === goodsItem.proid)
		if (oldGoods) {
			oldGoods.number = goodsItem.number
		}
	}

	// 删除购物车中商品
	const deleteGoodsById = (proid : string) => {
		cartList.value = cartList.value.filter(item => item.proid !== proid)
	}

	// 计算商品的总数
	const totalCount = computed(() => cartList.value.reduce((total, item) => total + item.number, 0))

	// 计算选中商品的总金额
	const selectTotalAmount = computed(() => cartList.value.filter(item => item.checked).reduce((total, item) => total + item.number * item.price, 0).toFixed(2))

	// 计算是否全选
	const isAllSelect = computed(() => cartList.value.every(item => item.checked))

	// 全选 & 反选
	const selectAll = (checked : boolean) => {
		cartList.value.forEach(item => {
			item.checked = checked
		})
	}

	return {
		cartList,
		addToCart,
		changeGoodsState,
		changeGoodsNumber,
		deleteGoodsById,
		totalCount,
		selectTotalAmount,
		isAllSelect,
		selectAll
	}
}, {
	persist: {
		storage: {
			setItem(key, value) {
				uni.setStorageSync(key, value)
			},
			getItem(key) {
				return uni.getStorageSync(key)
			}
		}
	}
})